package com.jwq.bsdw.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jwq.bsdw.pojo.Blog;
import com.jwq.bsdw.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/news")
public class BlogController {


    @Autowired
    private BlogService blogService;

    /**
     * 新闻添加
     *
     * @param model
     * @return
     */
    @GetMapping("/blogs/input")
    public String input(Model model) {

        //model.addAttribute("blog", new Blog());
        return "blogs-input";
    }

    /**
     * 公用（保存和修改）
     *
     * @param blog
     * @param attributes
     * @param session
     * @return
     */
    @PostMapping("/blogs")
    @ResponseBody
    public String post(Blog blog, RedirectAttributes attributes, HttpSession session) {
        //拿到当前的登录用户端的seesion

        Integer b;
        if (blog.getId() == null) {
            b = blogService.saveBlog(blog);
        } else {
            b = blogService.updateBlog(blog.getId(), blog);
        }

        if (b <= 0) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "success";
    }

    @GetMapping("/findByPage/{pageNum}/{pageSize}")
    @ResponseBody
    public IPage post(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        pageNum = pageNum <= 0 ? 1 : pageNum;
        pageSize = pageSize < 5 ? 5 : pageSize;
        return blogService.findByPage(pageNum, pageSize);
    }

}
